package com.pearlsoft.webapp.core.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pearlsoft.webapp.core.web.session.SessionProfile;
import com.pearlsoft.webapp.core.web.util.HttpUtil;
/**
 * 请求过滤器主要功能：
 * 1、判断用户是否登入,如果未登入，转入登入页面
 * @author YEHH
 */
public class SmartHttpRequestFilter implements Filter {
	protected static final Log logger = LogFactory.getLog(SmartHttpRequestFilter.class);
	
    private static final String FILTER_APPLIED = "__session_context_filter_applied";
    private static final String[] INHERENT_ESCAPE_URIS = {"/index.jsp","/pages/login.jsp"};
    private static final String HOME_URL ="/pages/home.jsp";
	public void destroy() {
		// TODO Auto-generated method stub

	}
	/**
	 * 登入验证
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 保证该过滤器在一次请求中只被调用一次
		 HttpServletRequest httpRequest = (HttpServletRequest) request;
		if(request!=null&&request.getAttribute(FILTER_APPLIED)!=null){
			chain.doFilter(request, response);
		}else {
			//设置过滤标识，防止一次请求多次过滤
            request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
            
            if(isURIEscape(httpRequest.getRequestURI(), httpRequest)){
            	chain.doFilter(request, response);
            }else if(!isLogin(httpRequest)){
            	request.getRequestDispatcher("/index.jsp").forward(request, response);
                return;
            }else if (httpRequest.getRequestURI().indexOf(HOME_URL)>=0){
            	chain.doFilter(request, response);
            }else if(!isRight(httpRequest)){
            	request.getRequestDispatcher("/pages/noRight.jsp").forward(request, response);
            	return;
            }else{
            	chain.doFilter(request, response);
            }
		}

	}
	private boolean isLogin( HttpServletRequest httpRequest){
	     Cookie nameCookie  = HttpUtil.getCookieByName(httpRequest,SessionProfile.COOKIE_USERNAME);
         Cookie stateCookie  = HttpUtil.getCookieByName(httpRequest,SessionProfile.COOKIE_STATE);
         if(nameCookie!=null && stateCookie!=null){
        	 String state = new String(Base64.decodeBase64(stateCookie.getValue().getBytes()));
        	 if(state.equals(SessionProfile.USER_STATE_LOGIN)){
        		 return true;
        	 }
        	 return false;
         }
         return false;
		
	}
	
	private boolean isRight(HttpServletRequest httpRequest){
//		String contextPath = httpRequest.getContextPath();
//		String url = httpRequest.getRequestURI().replace(contextPath,"");
//		logger.info("request url is "+url);
//		Cookie codeCookie  = HttpUtil.getCookieByName(httpRequest,SessionProfile.COOKIE_USERCODE);
//		String usercode =  new String(Base64.decodeBase64(codeCookie.getValue().getBytes()));
//		if(usercode==null){
//			return false;
//		}
//		Date now = new Date();
//		DateFormat d1 = DateFormat.getDateTimeInstance();
//		logger.info("开始判断时间："+d1.format(now));
//		boolean result = RightUtil.isRight(usercode, url);
//		Date now2 = new Date();
//		logger.info("结束判断时间："+d1.format(now2));
		return true;
	}
	
    private boolean isURIEscape(String requestURI, HttpServletRequest request) {
    	String contextPath = request.getContextPath();
        if (contextPath.equalsIgnoreCase(requestURI) || (contextPath + "/").equalsIgnoreCase(requestURI))
            return true;
        for (String uri : INHERENT_ESCAPE_URIS) {
            if (requestURI != null && requestURI.indexOf(uri) >= 0) {
                return true;
            }
        }
        return false;
    }
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
}
